package connectionpool;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 */
public class C3P0Executor {
    private final ComboPooledDataSource dataSource;
    
    public ComboPooledDataSource getDataSource() {
        return dataSource;
    }
    
    public C3P0Executor(String url, String username, String password) {
        dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setDataSourceName("C3P0 connection pool");
        dataSource.setUser(username);
        dataSource.setPassword(password);
    }
    
    public C3P0Executor(String url, String username, String password, int minIdle, int maxSize) {
        dataSource = new ComboPooledDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setDataSourceName("C3P0 connection pool");
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setMaxIdleTime(minIdle);
        dataSource.setMaxPoolSize(maxSize);
    }
    
    public void executeSQL(String sql) throws SQLException {
        try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) {
            System.err.println(sql);
            printResultSet(resultSet);
        }
    }
    
    private void printResultSet(ResultSet resultSet) throws  SQLException {
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnsNumber = rsmd.getColumnCount();
        while (resultSet.next()) {
            for (int i = 1; i <= columnsNumber; i++) {
                if (i > 1) {
                    System.err.print(", ");
                }
                String columnValue = resultSet.getString(i);
                System.err.print(rsmd.getColumnName(i) + ": " + columnValue);
            }
            System.err.println("");
        }
    }
    
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void close() {
        dataSource.close();
    }
}
